package de.blitzcoder.collide.gui.fileexplorer;

import de.blitzcoder.collide.Config;
import java.io.File;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.ListIterator;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreePath;

/**
 *
 * @author blitzcoder
 */
public class FileTree extends JTree implements TreeSelectionListener {

    private FileTable table;
    
    public FileTree(FileTable table) {
        this.table = table;
        addTreeSelectionListener(this);
        setModel(new FileTreeModel());
        //expandRow(1); // Expand root on unix systems, c: on windows
        expandLastTreePath(new File(Config.getProperty("fileexplorer.lastpath")));
    }

    public void valueChanged(TreeSelectionEvent e) {
        Object node_ = e.getPath().getLastPathComponent();
        if (node_ instanceof FileSystemNode) {
            FileSystemNode node = (FileSystemNode)node_;
            Config.setFileProperty("fileexplorer.lastpath", node.getFile());
            table.setDir(node.getFile());
        }
    }

    private void expandLastTreePath(File file) {
        DefaultMutableTreeNode root = (DefaultMutableTreeNode)getModel().getRoot();

        LinkedList<File> path = new LinkedList<File>();
        path.addLast(file);
        while (true) {
            file = file.getParentFile();
            if (file == null)
                break;
            path.addFirst(file);
        }

        LinkedList<MutableTreeNode> treePath = new LinkedList<MutableTreeNode>();
        treePath.addFirst(root);

        ListIterator<File> it = path.listIterator();
        MutableTreeNode node = root;
        while (it.hasNext()) {

            file = it.next();

            Enumeration e = node.children();
            while (e.hasMoreElements()) {
                FileSystemNode childNode = (FileSystemNode)e.nextElement();
                if (childNode.getFile().equals(file)) {
                    treePath.addLast(childNode);
                    node = childNode;
                    break;
                }
            }

        }
        
        expandPath(new TreePath(treePath.toArray()));

    }

}
